﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using SpeechLib;
using System.Threading;

class SonificationThread
{

    private SpVoice spVoice;
    private SpeechVoiceSpeakFlags svsp;
    private DateTime lastSpeechTS;
    private String lastCommand;
    private int speakInterval = 5; // seconds
    private List<String> queue;
    private object queueLock = new object();
    private Thread thread;
    public SonificationThread()
    {
        spVoice = new SpVoice();
        svsp = new SpeechVoiceSpeakFlags();
        lastCommand = null;
        queue = new List<String>();
    }
    public void ThreadProc()
    {
        
        String cmd = "nothing";
        lock (queueLock)
        {
            if (queue.Count == 0) return;
            cmd = queue[queue.Count - 1];
            queue.Clear();
        }
        
        //spVoice.Skip("Sentence", 1);
        
        //MessageBox.Show(lastCommand);
        lastSpeechTS = DateTime.Now;
        
        spVoice.Speak(lastCommand, svsp);
        spVoice.WaitUntilDone(2000);
        thread = null;
    }
    public void speak(String str)
    {
        if (str == null) return;

        if (str.Equals(lastCommand))
        {
            // only speak the same command it if its been the provided amount of time
            if (lastSpeechTS != null)
            {
               // MessageBox.Show((DateTime.Now.Ticks - lastSpeechTS.Ticks)+"");
                if (DateTime.Now.Subtract(lastSpeechTS).Seconds < speakInterval)
                {
                    return; // not enough time has passed
                }

            }
            else
            {
                // let it speak
            }
        }
        else {   }


        if (thread != null) return;
        queue.Add(str);
        lastCommand = str;
        thread = new Thread(new ThreadStart(ThreadProc));
        thread.Start();
        
    }
}
      